package com.seeyon.apps.bense.bank.manager;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;

import com.aspose.imaging.internal.hC.iF;
import com.seeyon.apps.bense.bank.core.OpenSDKClient;
import com.seeyon.apps.bense.bank.enums.BankAPIEnum;
import com.seeyon.apps.bense.common.domain.Cap4Update;
import com.seeyon.apps.bense.common.domain.Cap4Where;
import com.seeyon.apps.bense.common.manager.CAP4FormDataManagerExt;
import com.seeyon.apps.bense.util.CAP4FormKit;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.log.CtpLogFactory;
import org.apache.commons.logging.Log;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static com.seeyon.apps.bense.bank.core.Constants.*;

public class DealPayImpl {
    private static final Log LOGGER = CtpLogFactory.getLog(DealPayImpl.class);

    private CAP4FormDataManagerExt cap4FormDataManagerExt = (CAP4FormDataManagerExt) AppContext.getBean("cap4FormDataManagerExt");

    private OpenSDKClient openSDKClient = (OpenSDKClient) AppContext.getBean("openSDKClient");

    public void processData(String formCode, FormBean formBean, FormDataMasterBean master) {
        if (paymentTab.equals(formCode)) {
            LOGGER.info("=============开始执行费用报销单推送银行==============");
            processPayment(formBean, master);
            LOGGER.info("=============结束执行费用报销单推送银行==============");
            return;
        }
        if (paymentApplyTab.equals(formCode)) {
            LOGGER.info("=============开始执行付款申请单推送银行==============");
            processPaymentApply(formBean, master);
            LOGGER.info("=============结束执行付款申请单推送银行==============");
            return;
        }
        if (travelPaymentTab.equals(formCode)) {
            LOGGER.info("=============开始执行差旅费报销单推送银行==============");
            processTravelPayment(formBean, master);
            LOGGER.info("=============结束执行差旅费报销单推送银行==============");
            return;
        }

        LOGGER.info("=============未匹配到执行业务==============");
    }

    public void processTravelPayment(FormBean formBean, FormDataMasterBean master) {
     	//为了防止重复提交-启用新的字段，该字段与流水号绑定
//        String billCode = CAP4FormKit.getFieldStrValue(master, "差旅费报销编号");
    	String billCode = CAP4FormKit.getFieldStrValue(master, "付款请求号");

        String amt = CAP4FormKit.getFieldStrValue(master, "3.13本次支付金额");
        String corpCode = CAP4FormKit.getFieldStrValue(master, "单位代码");
        String rcvAcc = CAP4FormKit.getFieldStrValue(master, "收款银行账号");
        String payAcc = CAP4FormKit.getFieldStrValue(master, "付款银行账号");
        String rcvName = CAP4FormKit.getFieldStrValue(master, "3.18银行账户");//收款银行账户
        String purpose = CAP4FormKit.getFieldStrValue(master, "3.8备注");
        String rcvBankName = CAP4FormKit.getFieldStrValue(master, "3.19开户银行");//收款银行开户行
        String payBankName = CAP4FormKit.getFieldStrValue(master, "付款银行名称");
        String repPayAcc = CAP4FormKit.getFieldStrValue(master, "代支付银行账号");
        //String rcvBankNo = CAP4FormKit.getFieldStrValue(master, "收款方联行号");
        // 0或者空：直接付款 1：代理支付
        String payType = CAP4FormKit.getFieldStrValue(master, "支付方式");

        Map<String, Object> paramMap = new HashMap<>();
        //交易流水号，自己生成
        paramMap.put("serialNo", billCode);
        //金额
        paramMap.put("amt", amt);
        paramMap.put("corpCode", corpCode);
        paramMap.put("rcvAcc", rcvAcc);
        paramMap.put("payAcc", payAcc);
        paramMap.put("rcvName", rcvName);
        paramMap.put("purpose", purpose);
        paramMap.put("rcvBankName", rcvBankName);
        //自动请款 
        if("中国农业银行".equals(payBankName)){
        	//0:直接支付 1:代理支付 2:联动支付 3:自动请款 该字段默认为空，表示直接付款。
            paramMap.put("payType", "3");
            paramMap.put("remarkAcc", repPayAcc);//代理/联动账号/拨款账号
            paramMap.put("money", amt);//请款金额
        }else {
        	paramMap.put("payType", "0");
		}
        Map<String, Object> result = openSDKClient.sendRequest(BankAPIEnum.SINGLE_TRANSFER.url(), paramMap);
        LOGGER.info("差旅报销单调用银行接口结果="+result);
        Map<String, Object> dataMap = MapUtil.get(result, "Data", Map.class);
//        Assert.notNull(dataMap, "调用银行财资系统接口失败, serviceId = {}", BankAPIEnum.SINGLE_TRANSFER.url());
        if (!"0000".equals(dataMap.get("retCode"))) {
            //String message = String.format("调用接口【%s】异常, %s", BankAPIEnum.SINGLE_TRANSFER.url(), Optional.ofNullable(dataMap.get("retMsg")).orElse("未知原因【财资未返回异常原因】"));
        	 String message = (String) dataMap.get("retMsg");
        	throw new RuntimeException(message);
        }

        // 更新待回执状态
        FormFieldBean fieldBean = CAP4FormKit.getFieldBean(formBean.getMasterTableBean(), "回执状态");
        Assert.notNull(fieldBean, "表单【{}】,字段【{}】定义不存在", formBean.getFormName(), "回执状态");
        Cap4Where cap4Where = new Cap4Where();
        cap4Where.eq(CAP4FormKit.getFieldBean(formBean.getMasterTableBean(), "付款请求号").getName(), billCode);
        Cap4Update cap4Update = new Cap4Update();
        cap4Update.add(fieldBean.getName(), "否");
        cap4FormDataManagerExt.update(master.getFormTable(), cap4Update, cap4Where);
    }

    public void processPaymentApply(FormBean formBean, FormDataMasterBean master) {
    	
    	//为了防止重复提交-启用新的字段，该字段与流水号绑定
//        String billCode = CAP4FormKit.getFieldStrValue(master, "付款编号");
        String billCode = CAP4FormKit.getFieldStrValue(master, "付款请求号");
        String amt = CAP4FormKit.getFieldStrValue(master, "4.1本次支付金额");
        String corpCode = CAP4FormKit.getFieldStrValue(master, "单位代码");
        String rcvAcc = CAP4FormKit.getFieldStrValue(master, "收款银行账号");
        String payAcc = CAP4FormKit.getFieldStrValue(master, "付款银行账号");
        String rcvName = CAP4FormKit.getFieldStrValue(master, "3.1收款单位");//收款银行账户
        String purpose = CAP4FormKit.getFieldStrValue(master, "3.12付款事由");
        String rcvBankName = CAP4FormKit.getFieldStrValue(master, "3.4开户银行");//收款银行开户行
        String payBankName = CAP4FormKit.getFieldStrValue(master, "付款银行名称");
        String repPayAcc = CAP4FormKit.getFieldStrValue(master, "代支付银行账号");
        
        Assert.notBlank(billCode, "付款申请编号不能为空");
        Assert.notBlank(amt, "4.1本次支付金额");
        Assert.notBlank(rcvAcc, "收款银行账号不能为空");
        Assert.notBlank(payAcc, "付款银行账号不能为空");
        Assert.notBlank(rcvName, "3.1收款单位不能为空");
        Assert.notBlank(purpose, "3.12付款事由不能为空");
        Assert.notBlank(rcvBankName, "3.4开户银行不能为空");
        Assert.notBlank(corpCode, "单位代码不能为空");

        //String rcvBankNo = CAP4FormKit.getFieldStrValue(master, "收款方联行号");
        // 0或者空：直接付款 1：代理支付
        String payType = CAP4FormKit.getFieldStrValue(master, "支付方式");

        Map<String, Object> paramMap = new HashMap<>();
        //交易流水号，自己生成
        paramMap.put("serialNo", billCode);
        //金额
        paramMap.put("amt", amt);
        paramMap.put("corpCode", corpCode);
        paramMap.put("rcvAcc", rcvAcc);
        paramMap.put("payAcc", payAcc);
        paramMap.put("rcvName", rcvName);
        paramMap.put("purpose", purpose);
        paramMap.put("rcvBankName", rcvBankName);
        //自动请款 
        if("中国农业银行".equals(payBankName)){
        	//0:直接支付 1:代理支付 2:联动支付 3:自动请款 该字段默认为空，表示直接付款。
            paramMap.put("payType", "3");
            paramMap.put("remarkAcc", repPayAcc);//代理/联动账号/拨款账号
            paramMap.put("money", amt);//请款金额
        }else {
        	paramMap.put("payType", "0");
		}
        Map<String, Object> result = openSDKClient.sendRequest(BankAPIEnum.SINGLE_TRANSFER.url(), paramMap);
        LOGGER.info("付款单调用银行接口结果="+result);
        Map<String, Object> dataMap = MapUtil.get(result, "Data", Map.class);
        LOGGER.info("付款单调用银行接口结果dataMap="+dataMap);
//        Assert.notNull(dataMap, "调用银行财资系统接口失败, serviceId = {}", BankAPIEnum.SINGLE_TRANSFER.url());
        if (!"0000".equals(dataMap.get("retCode"))) {
        	String message = (String) dataMap.get("retMsg");
            throw new RuntimeException(message);
        }

        // 更新待回执状态
        FormFieldBean fieldBean = CAP4FormKit.getFieldBean(formBean.getMasterTableBean(), "回执状态");
        Assert.notNull(fieldBean, "表单【{}】,字段【{}】定义不存在", formBean.getFormName(), "回执状态");
        Cap4Where cap4Where = new Cap4Where();
        cap4Where.eq(CAP4FormKit.getFieldBean(formBean.getMasterTableBean(), "付款请求号").getName(), billCode);
        Cap4Update cap4Update = new Cap4Update();
        cap4Update.add(fieldBean.getName(), "否");
        cap4FormDataManagerExt.update(master.getFormTable(), cap4Update, cap4Where);
    }

    public void processPayment(FormBean formBean, FormDataMasterBean master) {
      	//为了防止重复提交-启用新的字段，该字段与流水号绑定
//        String billCode = CAP4FormKit.getFieldStrValue(master, "费用报销编号");
        String billCode = CAP4FormKit.getFieldStrValue(master, "付款请求号");
        String amt = CAP4FormKit.getFieldStrValue(master, "3.1报销金额");
        // 存疑
        String corpCode = CAP4FormKit.getFieldStrValue(master, "单位代码");
        String rcvAcc = CAP4FormKit.getFieldStrValue(master, "收款银行账号");
        String payAcc = CAP4FormKit.getFieldStrValue(master, "付款银行账号");
        String rcvName = CAP4FormKit.getFieldStrValue(master, "3.10收款银行账户");
        String purpose = CAP4FormKit.getFieldStrValue(master, "3.16备注");
        String rcvBankName = CAP4FormKit.getFieldStrValue(master, "3.11开户银行");
        String payBankName = CAP4FormKit.getFieldStrValue(master, "付款银行名称");
        String repPayAcc = CAP4FormKit.getFieldStrValue(master, "代支付银行账号");
        //String rcvBankNo = CAP4FormKit.getFieldStrValue(master, "收款方联行号");
        // 0或者空：直接付款 1：代理支付
//        String payType = CAP4FormKit.getFieldStrValue(master, "支付方式");

        Assert.notBlank(billCode, "费用报销编号不能为空");
        Assert.notBlank(amt, "3.1报销金额不能为空");
        Assert.notBlank(rcvAcc, "3.12银行账号不能为空");
        Assert.notBlank(payAcc, "贷方科目不能为空");
        Assert.notBlank(rcvName, "3.10收款银行账户不能为空");
        //Assert.notBlank(purpose, "3.16备注不能为空");
        Assert.notBlank(rcvBankName, "3.11开户银行不能为空");
        Assert.notBlank(corpCode, "部门编码不能为空");

        Map<String, Object> paramMap = new HashMap<>();
        //交易流水号，自己生成
        paramMap.put("serialNo", billCode);
        //金额
        paramMap.put("amt", amt);
        // 单位代码
        paramMap.put("corpCode", corpCode);
        // 收款账号
        paramMap.put("rcvAcc", rcvAcc);
        // 付款账号
        paramMap.put("payAcc", payAcc);
        // 收款户名
        paramMap.put("rcvName", rcvName);
        // 用途
        paramMap.put("purpose", purpose);
        // 收款方行名
        paramMap.put("rcvBankName", rcvBankName);
        //自动请款 
        if("中国农业银行".equals(payBankName)){
        	//0:直接支付 1:代理支付 2:联动支付 3:自动请款 该字段默认为空，表示直接付款。
            paramMap.put("payType", "3");
            paramMap.put("remarkAcc", repPayAcc);//代理/联动账号/拨款账号
            paramMap.put("money", amt);//请款金额
        }else {
        	paramMap.put("payType", "0");
		}
        
        Map<String, Object> result = openSDKClient.sendRequest(BankAPIEnum.SINGLE_TRANSFER.url(), paramMap);
        LOGGER.info("费用报销单调用银行接口结果="+result);
        Map<String, Object> dataMap = MapUtil.get(result, "Data", Map.class);
        LOGGER.info("费用报销单调用银行接口结果dataMap="+dataMap);
        //Assert.notNull(dataMap, "调用银行财资系统接口失败, serviceId = {}", BankAPIEnum.SINGLE_TRANSFER.url());
        if (!"0000".equals(dataMap.get("retCode"))) {
            String message = (String) dataMap.get("retMsg");
            throw new RuntimeException(message);
        }

        // 更新待回执状态
        FormFieldBean fieldBean = CAP4FormKit.getFieldBean(formBean.getMasterTableBean(), "回执状态");
        Assert.notNull(fieldBean, "表单【{}】,字段【{}】定义不存在", formBean.getFormName(), "回执状态");
        Cap4Where cap4Where = new Cap4Where();
        cap4Where.eq(CAP4FormKit.getFieldBean(formBean.getMasterTableBean(), "付款请求号").getName(), billCode);
        Cap4Update cap4Update = new Cap4Update();
        cap4Update.add(fieldBean.getName(), "否");
        cap4FormDataManagerExt.update(master.getFormTable(), cap4Update, cap4Where);
    }
}
